<?php

namespace App\Utils;

use App\Models\Files;
use App\Models\System\File;
use Loongjoy\SDK\Storage;

class Plist
{
    public static function make(string $appName, string $appId, string $version, string $url)
    {
        $plist_str = self::splitString($appName, $appId, $version, $url);

        $file = date('His') . '.plist';
        $path = 'public/' . date('Ymd') . '/' . $file;
        \Illuminate\Support\Facades\Storage::put($path, implode('', $plist_str));

        $inFile = new File();
        $inFile->name = $file;
        $inFile->module = 1;
        $inFile->type = 1;
        $inFile->md5 = '';
        $inFile->path = $path;
        $inFile->save();
        return $inFile['id'];
    }

    private static function splitString(string $appName, string $appId, string $version, string $url)
    {
        $string[] = '<?xml version="1.0" encoding="UTF-8"?>';
        $string[] = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">';
        $string[] = '<plist version="1.0">';
        $string[] = '<dict>';
        $string[] = '<key>items</key>';
        $string[] = '<array>';
        $string[] = '<dict>';
        $string[] = '<key>assets</key>';
        $string[] = '<array>';
        $string[] = '<dict>';
        $string[] = '<key>kind</key>';
        $string[] = '<string>software-package</string>';
        $string[] = '<key>url</key>';
        $string[] = '<string>' . $url . '</string>';
        $string[] = '</dict>';
        $string[] = '</array>';
        $string[] = '<key>metadata</key>';
        $string[] = '<dict>';
        $string[] = '<key>bundle-identifier</key>';
        $string[] = '<string>' . $appId . '</string>';
        $string[] = '<key>bundle-version</key>';
        $string[] = '<string>' . $version . '</string>';
        $string[] = '<key>kind</key>';
        $string[] = '<string>software</string>';
        $string[] = '<key>title</key>';
        $string[] = '<string>' . $appName . '顾问端' . '</string>';
        $string[] = '</dict>';
        $string[] = '</dict>';
        $string[] = '</array>';
        $string[] = '</dict>';
        $string[] = '</plist>';

        return $string;
    }
}
